package com.onlinevideo.util;

import com.onlinevideo.data.MyConst;
import com.onlinevideo.entity.User;
import com.onlinevideo.entity.Video;
import com.onlinevideo.entity.VideoItem;
import com.onlinevideo.service.impl.VideoServiceImpl;
import org.apache.commons.fileupload.FileItem;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class FileUpLoadUtils {

    /***
     *
     * @param files 数据源
     * @return Map K-上传的文件类型;  V-上传后的地址，若无效，则为-1
     *
     * 视频文件的上传文件名字格式: 数字_文件名.mp4
     */
    /*
    *返回的数据需要  1，将图片的上传格式
     */
    public static Map<String,Map<String,String>> uploadFileUtils(List<FileItem> files){
        //原文件名字  文件上传地址
        Map<String,String> videoFileUrl = new HashMap<>();
        Map<String,String> imgFileUrl = new HashMap<>();
        Map<String,Map<String,String>> maps = new HashMap<>();

/*        int videoCount = 0;
        //如果有视频名字格式不规范则返回null
        for (FileItem fileItem : files) {
            String contentType = fileItem.getContentType();
            if(contentType.startsWith("video")){
                videoCount++;
                String fileName = fileItem.getName();
                String[] s = fileName.split("_");
                if(!(s.length == 2 && s[0].matches("[0-9]+"))){
                    return null;
                }
            }
        }
        //如果没有上传视频子集则返回null
        if (videoCount==0){
            return null;
        }*/


        for (FileItem fileItem :files) {
            String contentType = fileItem.getContentType();
            String fileName = fileItem.getName();
            //处理视频文件
            String folder = contentType.substring(0, contentType.lastIndexOf("/"));
            StringBuilder url = new StringBuilder(MyConst.FILE_UPLOAD_PATH+folder+"s/" + System.currentTimeMillis()+"_" + fileName);
            try {
                String[] s = fileName.split("_");
                if(contentType.startsWith("video")){
                    if(!(s.length == 2 && s[0].matches("[0-9]+"))){
                        continue;
                    }
                }
                fileItem.write(new File("D:"+String.valueOf(url)));
                String name = fileName.substring(0, fileName.lastIndexOf("."));
                if(contentType.startsWith("video")){
                    videoFileUrl.put(name,String.valueOf(url));
                }else if(contentType.startsWith("image")){
                    imgFileUrl.put(name,String.valueOf(url));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        maps.put("video",videoFileUrl );
        maps.put("image",imgFileUrl );
        return maps;
    }



    public static boolean isVideo(String name) {
        String[] s = name.split("\\.");
        String last = s[s.length - 1];
        if (last == null) {
            return false;
        }
        String[] videoLast = MyConst.VIDEO_LAST;
        for (int i = 0; i < videoLast.length; i++) {
            if (videoLast[i].equalsIgnoreCase(last)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isImg(String name) {
        String[] s = name.split("\\.");
        String last = s[s.length - 1];
        if (last == null) {
            return false;
        }
        String[] imgLast = MyConst.IMG_LAST;
        for (int i = 0; i < imgLast.length; i++) {
            if (imgLast[i].equalsIgnoreCase(last)) {
                return true;
            }
        }
        return false;
    }

    public static Map<String, Object> getVideoInfo(List<FileItem> fileList, User user) {
        Video video = FileUpLoadUtils.newVideo();
        Map<String, Object> map = new HashMap<>();
        List<File> files = new ArrayList<>();
        List<FileItem> fileItems = new ArrayList<>();
        List<VideoItem> videoItems = new ArrayList<>();
        List<FileItem> fileList1 = fileList;
        //处理文件数据




        for (FileItem f : fileList) {
            //是表单项 则都是Video的属性
            if (f.isFormField()) {
                map.put(f.getFieldName(), new String(f.getString().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
            //不是表单项（是文件） 需要创建file存入硬盘 生成url存入数据库
            } else {
                String fieldName = f.getFieldName();
                String fName = f.getName();
                //如果该属性是视频 （可能有多个）
                // 如果格式是视频
                if ("video".equals(fieldName) && FileUpLoadUtils.isVideo(fName)) {
                    VideoItem videoItem = new VideoItem();
                    videoItem.setVideoId(video.getId());
                    String videoUrl = getVideoName(fName);
                    videoItem.setUrl(videoUrl);
                    String[] split = fName.split("_");
                    if (split.length >= 2 || split[0].matches("[0-9]+")) {
                        videoItem.setSortCount(Integer.valueOf(split[0]));
                        videoItem.setName(split[1].substring(0,split[1].lastIndexOf(".")));
                    }
                    videoItems.add(videoItem);
                    fileItems.add(f);
                    files.add(new File("D:" + getVideoName(fName)));
                }
                //如果该属性是图片（只有一个）
                // 如果格式是图片
                else if ("videoImg".equals(fieldName) && FileUpLoadUtils.isImg(fName)) {
                    files.add(new File("D:" + getImgName(fName)));
                    fileItems.add(f);
                    map.put("videoImg", getImgName(fName));

                }
            }
        }
        map.put("userId", user.getId());
        HashMap<String, Object> res = new HashMap<>();
        res.put("fileItems", fileItems);
        res.put("files", files);
        res.put("videoItems", videoItems);
        res.put("map", map);
        res.put("video", video);
        return res;
    }

    public static FileItem find(List<FileItem> fileItems,String name) throws Exception {
        if (name == null||fileItems==null) {
            return null;
        }
        for (FileItem fileItem : fileItems) {
            if (name.equals(fileItem.getFieldName())) {
                return fileItem;
            }
        }
        return null;
    }


    public static String getVideoName(String name) {
        return "/uploadFile/videos/" + System.currentTimeMillis() + "_" + name;
    }

    public static String getImgName(String name) {
        return "/uploadFile/images/" + System.currentTimeMillis() + "_" + name;
    }

    public static Video newVideo() {
        VideoServiceImpl videoService = new VideoServiceImpl();
        Video video = new Video();
        int i = new Random().nextInt(100000);
        video.setVideoName(String.valueOf(i));
        long l = System.currentTimeMillis();
        String uploadTime = String.valueOf(l);
        video.setUploadTime(uploadTime);
        videoService.insert(video);
        List<Video> videos = videoService.queryByConditions(video);
        video = videos.get(0);
        return video;
    }
}
